
// 110.平衡二叉树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        // 看每个节点的左右子树高度
        bool ret = true;
        function<int(TreeNode*)> height = [&](TreeNode* pos)
        {   
            if(pos->left == nullptr && pos->right == nullptr) return 1;
            int l = 1 , r = 1;
            if(pos->left) l = height(pos->left) +1;
            if(pos->right) r = height(pos->right) + 1;

            if(abs(l - r) > 1) ret = false;
            return max(l , r);
        };         
        if(root) height(root);
        return ret;
    }
};